﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.SessionState;

namespace Kaiser.Utilities.Captcha
{
 

    public class ImageResult : ActionResult
    {
        public Image imageData;

        public ImageResult(Image image)
        {
            imageData = image;
        }

        public override void ExecuteResult(ControllerContext context)
        {
             if (context == null)
             {
                 throw new ArgumentNullException("context");
             }

             HttpResponseBase response = context.HttpContext.Response;

             response.ContentType = "image/bmp";

             using (MemoryStream ms = new MemoryStream())
             {
                 imageData.Save(ms, ImageFormat.Bmp);
                 context.HttpContext.Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
             }

            // imageData.Save(context.HttpContext.Response.OutputStream, ImageFormat.Bmp);
        }

    }

    public class CaptchaUtil
    {
        private static readonly int _bufferSize = 0x1000;
        private static readonly string _defaultKey = "CAPTCHA";
        public static string DefaultKey {
            get { return _defaultKey; }
        }
   

        public static bool Check(string value)
        {
            return Check(_defaultKey, value);
        }

        public static bool Check(string code, string value)
        {
            var serverValue = HttpContext.Current.Session[code] == null ? "" : HttpContext.Current.Session[code].ToString();
            if (string.IsNullOrEmpty(serverValue))
            {
                return false;
            }
            else if (value.ToLower() != serverValue.ToLower())
            {
                return false;
            }
            else
            {
                return true;
            }
        }
         
    }
}
